/*
 * @Description: 
 * @Autor: starzhou
 * @Date: 2020-08-31 20:34:35
 * @LastEditTime: 2020-09-07 12:04:32
 */
import axios from 'axios'
import { Notification } from 'element-ui';
// 创建axios实例
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? '/admin' : '', // api的base_url
  timeout: 10000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  var token = sessionStorage.getItem('apptoken');
  if (token && config.url != '/login') {
    config.headers['Authorization'] = token
  }
  return config
}, error => {
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  ({ data, config }) => {
    if (data.code == 200) {
      if (config.url == '/logout') {
        sessionStorage.removeItem('apptoken');
        // sessionStorage.removeItem('menuList');
        // sessionStorage.removeItem('roleId');
        window.location.reload()
      }
      if (config.url == '/login') {
        sessionStorage.setItem('apptoken', data.token)
      }
      return data
    } else {
      data.msg = data.msg ? data.msg : '网络错误';
      Notification.error({
        title: '错误',
        message: data.msg
      });
      if (data.code == 401 || data.code == 402){
        sessionStorage.removeItem('apptoken');
        window.location.reload()
      }
      return Promise.reject(new Error(data.msg))
    }
  },
  error => {
    console.log('err' + error)
    return Promise.reject(error)
  }
)

export default service
